package sspatcher;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class CSVHelper {

    public static List<List<String>> readCsvFromFile(File file, boolean containHeader) throws Exception {
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        if (containHeader)
        {
            br.readLine(); // consume header
        }

        List<List<String>> result = new ArrayList<>();

        int ch = br.read();
        byte[] buffer = new byte[256];
        int buffer_idx = 0;
        boolean quoteFlag = false;
        List<String> lineElements = new ArrayList<>();
        while (ch != -1) {
            byte b = (byte)ch;
            switch (b) {
                case ' ':
                    if (quoteFlag) {
                        buffer[buffer_idx++] = b;
                    }
                    break;
                case '"':
                    quoteFlag = !quoteFlag;
                    break;
                case ',':
                    if (quoteFlag) {
                        buffer[buffer_idx++] = b;
                    }
                    else {
                        lineElements.add(new String(buffer, 0, buffer_idx, StandardCharsets.UTF_8));
                        buffer_idx = 0;
                    }
                    break;
                case '\n':
                    if (quoteFlag) throw new Exception("quote is not completed");
                    if (buffer_idx > 0) {
                        lineElements.add(new String(buffer, 0, buffer_idx, StandardCharsets.UTF_8));
                        buffer_idx = 0;
                    }
                    result.add(lineElements);
                    lineElements = new ArrayList<>();
                    break;
                default:
                    buffer[buffer_idx++] = b;
            }

            ch = br.read();
        }

        if (buffer_idx > 0) {
            lineElements.add(new String(buffer, 0, buffer_idx, StandardCharsets.UTF_8));
            buffer_idx = 0;
        }
        if (!lineElements.isEmpty()){
            result.add(lineElements);
        }

        return result;
    }
}
